//引入模块
const express = require("express");
const query = require("../util/query.js");
const JWT = require('../util/token.js');

//创建路由器对象
let router = express.Router();

//===============================================
//收藏模块
//================================================
//1.收藏列表 GET /collection/list
//参数:无(获取当前用户的所有记录)
router.get("/list", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  //获取数据:无  
  try {
    //获取当前用户的收藏
    let sql = `select id,product_id ,title,price,pic,is_checked from v_collection_item where is_checked=1 `;
    let result = await query(sql);
				
    let data = result;
    return res.send({ code: 1, msg: `收藏查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});
//查询is_checked
// post /collection/select
router.post("/select", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  //获取数据:无  
  try {
    //获取数据,验证数据 POST请求 从body中获取数据
    let product_id = req.body.product_id;
    if (!product_id) throw new Error("商品编号不能为空");
    
    //判断用户的收藏中是否已有该商品
    let sql = `SELECT is_checked FROM lz_collection_item WHERE product_id=${product_id}`;
    let result = await query(sql);
    let data = result;
    return res.send({ code: 1, msg: `is_checked查询成功`, data :data});
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


//2.添加收藏 POST /collection/add
// 参数名	       参数说明
// product_id	商品编号
// count 商品数量
router.post("/add", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据 POST请求 从body中获取数据
    let product_id = req.body.product_id;
    if (!product_id) throw new Error("商品编号不能为空");
    
    //判断用户的收藏中是否已有该商品
    let sql = `SELECT id FROM v_collection_item WHERE user_id=${user.id} AND product_id=${product_id}`;
    
    let result = await query(sql);
    //执行SQL语句 
    if (result.length <= 0) {
      //用户收藏已经有该商品，则加count
      sql = `INSERT INTO lz_collection_item(id,user_id,product_id,is_checked) VALUES(NULL, ${user.id}, ${product_id}, 1)`;
    }
    // console.log(sql);    
    result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: `收藏成功 ` });
    }
    throw new Error("操作失败"); 
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//3.删除收藏 GET /collection/delete  
// 参数名	       参数说明
// ids	多个编号(流水号)，用","分割"
router.get("/delete", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据
    let ids = req.query.ids;
    if (!ids) {
      throw new Error("编号（流水号)不能为空");
    }

    //执行SQL语句    
    let sql = `DELETE FROM lz_collection_item WHERE id = ${ids} `;
    //console.log(sql);

    let result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: `删除成功 ：ids=${ids}` });
    }
    throw new Error("操作失败");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

router.get("/del", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据
    let ids = req.query.ids;
    if (!ids) {
      throw new Error("编号（流水号)不能为空");
    }

    //执行SQL语句    
    let sql = `DELETE FROM lz_collection_item WHERE product_id = ${ids} `;
    //console.log(sql);

    let result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: `取消收藏 ` });
    }
    throw new Error("操作失败");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});



//===============================================
module.exports = router;